/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.manage.wallet;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.core.common.bean.ManageContainer;
import shop.core.common.dao.page.PagerModel;
import shop.services.manage.account.AccountService;
import shop.services.manage.account.bean.Account;
import shop.services.manage.brokerage.BrokerageService;
import shop.services.manage.brokerage.bean.Brokerage;
import shop.services.manage.organize.OrganizeService;
import shop.services.manage.organize.bean.Organize;
import shop.services.manage.record.RecordService;
import shop.services.manage.record.bean.Record;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;
import shop.services.manage.wallet.WalletService;
import shop.services.manage.wallet.bean.Wallet;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;

/**
 * @类名称：WalletAction
 * @创建人：Ltz
 * @创建时间：2017-08-12 上午10:15:30
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/wallet/")
public class WalletAction extends BaseController<Wallet> {
    private static final Logger logger = LoggerFactory.getLogger(WalletAction.class);
    @Autowired
    private WalletService walletService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private BrokerageService brokerageService;
    @Autowired
    private RecordService recordService;
    private static final String page_toList = "/manage/wallet/walletList";
    private static final String page_toDetail = "/manage/wallet/walletDetails";
    private static final String page_toCheckList = "/manage/wallet/walletCheck";
    private static final String page_toCheckEdit = "/manage/wallet/walletCheckEdit";
    private static final String page_toOrganizeList = "/manage/wallet/walletOrganizeList";
    private static final String page_toOrganizeCheck = "/manage/wallet/walletOrganizeCheck";

    public WalletService getService() {
        return walletService;
    }

    private WalletAction() {
        super.page_toList = page_toList;
        super.page_toAdd = null;
        super.page_toEdit = null;
    }

    /**
     * 跳转到提现审核页面
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toCheckEdit")
    public String toCheckEdit(@ModelAttribute("e") Wallet e, ModelMap model) throws Exception {
        e = walletService.selectOne(e);
        model.addAttribute("e", e);
        return page_toCheckEdit;
    }

    /**
     * 跳转到提现审核列表页面
     *
     * @return
     */
    @RequestMapping("toCheckList")
    public String toCheckList() {
        return page_toCheckList;
    }

    /**
     * 跳转到提现审核查看页面
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toDetail")
    public String toDetail(@ModelAttribute("e") Wallet e, ModelMap model) throws Exception {
        e = walletService.selectOne(e);
        model.addAttribute("e", e);
        return page_toDetail;
    }


    /**
     * 跳转到机构返利明细页面
     *
     * @return
     */
    @RequestMapping("toOrganizeList")
    public String toOrganizeList() {
        return page_toOrganizeList;
    }


    /**
     * 跳转到机构提现审核页面
     *
     * @return
     */
    @RequestMapping("toOrganizeCheckList")
    public String toOrganizeCheckList() {
        return page_toOrganizeCheck;
    }



    /**
     * 提现申请
     *
     * @return jsonResult
     * @throws Exception
     */
    @Override
    @RequestMapping(value = "insertJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertJson(HttpServletRequest request, @ModelAttribute("wallet") Wallet wallet) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        DecimalFormat df = new DecimalFormat("######0.00");
        Organize organize =new Organize();
        organize.setPrincipalPhone(user.getUsername());
        organize=organizeService.selectOne(organize);//查询账号所属机构
        if(Double.parseDouble(user.getUnCash())>=Double.parseDouble(wallet.getMoney())){
            wallet.setApplicant(user.getId());
            wallet.setApplicantType("2");
            wallet.setApplicantName(user.getNickname());
            wallet.setOrganizeName(organize.getName());
            wallet.setStatus("1");
            int rs = walletService.insert(wallet);//插入提现申请表
            user.setCash(String.valueOf(df.format(Double.parseDouble(user.getCash()) + Double.parseDouble(wallet.getMoney()))));//计算已提现
            user.setUnCash(String.valueOf(df.format(Double.parseDouble(user.getUnCash()) - Double.parseDouble(wallet.getMoney()))));//计算未提现
            userService.update(user);//更新用户信息
            Record record =new Record();
            record.setUserType("2");
            record.setUserID(user.getId());
            record.setTransType(wallet.getAccountType());
            record.setMoney(wallet.getMoney());
            record.setStatus("1");
            record.setwID(String.valueOf(rs));
            recordService.insert(record);//插入交易记录表
            return jsonResult;
        }else{
            jsonResult.setSuccess(false);
            jsonResult.setMessage("您的余额不足，无法进行提现！");
            return jsonResult;
        }
    }


    /**
     * 提现审核
     *
     * @return jsonResult
     * @throws Exception
     */
    @Override
    @RequestMapping(value = "updateJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateJson(HttpServletRequest request, @ModelAttribute("wallet") Wallet wallet) throws Exception {
        jsonResult = new JSONResult();
        getService().update(wallet);
        wallet = getService().selectOne(wallet);//查询提现记录
        DecimalFormat df = new DecimalFormat("######0.00");
        if (wallet.getStatus().equals("3")) {//判断审核状态
            if (wallet.getApplicantType().equals("1")) {//判断申请人类型
                Account account = new Account();
                account.setId(wallet.getApplicant());
                account = accountService.selectOne(account);
                account.setCash(String.valueOf(df.format(Double.parseDouble(account.getCash()) - Double.parseDouble(wallet.getMoney()))));//计算已提现
                account.setUnCash(String.valueOf(df.format(Double.parseDouble(account.getUnCash()) + Double.parseDouble(wallet.getMoney()))));//计算未提现
                accountService.update(account);//更新用户信息
//                request.getSession().setAttribute("accountInfo", account);//更新缓存
                Record record = new Record();
                record.setwID(wallet.getId());
                record = recordService.selectOne(record);//查询交易记录
                record.setStatus("3");
                record.setMoney(wallet.getMoney());
                recordService.update(record);//更新提现状态
                return jsonResult;
            } else if (wallet.getApplicantType().equals("2")) {//判断申请人类型
                User user = new User();
                user.setId(wallet.getApplicant());
                user = userService.selectOne(user);
                user.setCash(String.valueOf(df.format(Double.parseDouble(user.getCash()) - Double.parseDouble(wallet.getMoney()))));//计算已提现
                user.setUnCash(String.valueOf(df.format(Double.parseDouble(user.getUnCash()) + Double.parseDouble(wallet.getMoney()))));//计算未提现
                userService.update(user);//更新用户信息
//                request.getSession().setAttribute(ManageContainer.manage_session_user_info, user);//更新缓存
                Record record = new Record();
                record.setwID(wallet.getId());
                record = recordService.selectOne(record);
                record.setStatus("3");
                record.setMoney(wallet.getMoney());
                recordService.update(record);//更新提现状态
                return jsonResult;
            } else {
            }
        } else if (wallet.getStatus().equals("2")) {//判断审核状态
            if (wallet.getApplicantType().equals("1")) {
                Record record = new Record();
                record.setwID(wallet.getId());
                record = recordService.selectOne(record);//查询交易记录
                record.setStatus("2");
                recordService.update(record);//更新提现状态
                return jsonResult;
            } else if (wallet.getApplicantType().equals("2")) {
                Record record = new Record();
                record.setwID(wallet.getId());
                record = recordService.selectOne(record);//查询交易记录
                record.setStatus("2");
                recordService.update(record);//更新提现状态
                return jsonResult;
            } else {
            }
        } else {
        }
        jsonResult.setSuccess(false);
        return jsonResult;
    }

    /**
     * 查询提现总数
     *
     * @param wallet
     * @return
     */
    @RequestMapping(value = "selectCashSum", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectCashSum(@ModelAttribute("wallet") Wallet wallet) {
        int rs=0;
        try{
            rs = walletService.selectSum(wallet);
        }catch(Exception e){
            e.printStackTrace();
        }
        jsonResult = new JSONResult();
        jsonResult.setData(rs);
        return jsonResult;
    }


    /**
     * 查询未提现总数
     *
     * @param wallet
     * @return
     */
    @RequestMapping(value = "selectUnCashSum", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectUnCashSum(Wallet wallet,Brokerage brokerage) {
        int rs=0;int rs2=0;int rs3;
        try{
            rs = walletService.selectSum(wallet);
            rs2 =  brokerageService.selectNotAdminSum(brokerage);
        }catch(Exception e){
            e.printStackTrace();
        }
        rs3 =rs2 - rs;
        jsonResult = new JSONResult();
        jsonResult.setData(rs3);
        return jsonResult;
    }

    /**
     * 查询提现总数（机构）
     *
     * @param wallet
     * @return
     */
    @RequestMapping(value = "selectOrganizeSum", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrganizeSum(HttpServletRequest request,@ModelAttribute("wallet") Wallet wallet) {
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        wallet.setApplicantType("2");
        wallet.setApplicant(user.getId());
        int rs=0;
        try{
            rs = walletService.selectSum(wallet);
        }catch(Exception e){
            e.printStackTrace();
        }
        jsonResult = new JSONResult();
        jsonResult.setData(rs);
        return jsonResult;
    }

    /**
     * 查询机构提现申请记录
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("loadOrganizeData")
    @ResponseBody
    public PagerModel loadOrganizeData(HttpServletRequest request, Wallet e) {
        int offset = 0;
        int pageSize = 10;
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        e.setApplicantType(user.getId());
        e.setApplicantType("2");
        PagerModel pager = getService().selectPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }


    /**
     * 查询登录用户
     * @param
     * @return
     */
    @RequestMapping(value = "selectUser", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        jsonResult = new JSONResult();
        jsonResult.setData(user);
        return jsonResult;
    }

}
